<template>
    <!-- 虚拟滚动内容 -->
    <div class="virtual-scroller" @scroll="onScroll" :style="{ height: containerHeight + 'px' }" ref="scrollContainer">
        <!-- 实际渲染的列表内容 -->
        <ul class="real-list-content" :style="{ transform: `translateY(${translateY}px)` }">
            <li v-for="item in visibleList" :key="item.id" :style="{
                height: `${listItemHeight}px`,
                'line-height': `${listItemHeight}px`,
            }">
                <div>{{ item.name }}</div>
            </li>
        </ul>

        <!-- 虚拟列表元素 -->
        <div class="virtual-height" :style="{ height: virtualHeight + 'px' }">
            ~ 数据加载完毕 ~
        </div>
    </div>
</template>
  
<script>
import { throttle } from "@/utils/tools"; // 封装的函数节流
export default {
    name: "VirtualSelf",
    props: ["database"],
    created(){
       
    },
    data() {
        return {
            startIndex: 0,
            endIndex: 10,
            listItemHeight: 60,
            containerHeight: 300,
            translateY: 0,
            // visibleList: [],
            // virtualHeight: 100,
        }
    },
    computed: {
        visibleList() {
            return this.database.slice(this.startIndex, this.endIndex);
        },
        virtualHeight() {
            return (this.database.length - this.visibleList.length) * this.listItemHeight + this.listItemHeight
        },

    },
    methods: {
        onScroll:throttle(function() {
            console.log("111")
            const eleScrollTop = this.$refs.scrollContainer.scrollTop;
            // 保证实际渲染列表一直停留在可视区
            this.translateY = eleScrollTop;
            // 根据实际的滚动距离，动态计算列表开始索引
            this.startIndex = Math.floor(eleScrollTop / this.listItemHeight);
            // 基于开始索引
            this.endIndex = this.startIndex + 10;
        },200)
        // onNewScroll(){
        //     return throttle(this.onScroll,200)
        // }
        
    }
};
</script>
 
  
 
 
  
 
  
<style scoped>
.virtual-scroller {
    border: solid 1px #eee;
    margin-top: 10px;
    height: 600px;
    overflow: auto;
}

.virtual-height {
    /* background: red; */
    display: flex;
    align-items: flex-end;
    justify-content: center;
    color: #fff;
}

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

li {
    outline: solid 1px #fff;
    background-color: #000;
    color: #fff;
}
</style>
 